package net.ojbk.twobox.client;

import net.ojbk.twobox.pojo.TcpMessage;
import net.ojbk.twobox.server.FileReceiveServer;

import java.io.*;
import java.net.Socket;

/**
 * PACKAGE_NAME: net.ojbk.twobox.client
 * Description:
 */
public class SentFileClient {
    public static String FileReceiveServerIp = "ojbk.net";

    public static void main(String[] args) throws IOException {
        String fileAdd = args[0];
        File file = new File(fileAdd);
        // 连接服务器
        Socket socket = new Socket(FileReceiveServerIp, FileReceiveServer.localPort);
        // 获取流
        InputStream fileIn = new FileInputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        OutputStream tcpOut = socket.getOutputStream();
        // 发送相关信息
        TcpMessage tcpMessage = new TcpMessage();
        tcpMessage.code = 1;
        Object[] data = {file.getName(), file.length()};
        tcpMessage.data = data;
        objectOutputStream.writeObject(tcpMessage);
        objectOutputStream.flush(); // 这里如果加了flush，会导致接收到文件有问题。。。。
        // 发送文件
        byte[] bytes = new byte[1024]; // 缓冲区
        int len = -1;
        while ((len = fileIn.read(bytes)) != -1) { // 先fileIn 读到内存bytes中
            // 发送出去,最后一块可能不是1024，所以需要指定长度
            tcpOut.write(bytes, 0, len);
        }
        tcpOut.flush();
        // 关闭系列
        objectOutputStream.close();
        tcpOut.close();
        fileIn.close();
        socket.close();
        System.out.println("发送完成：" + fileAdd);
    }
}
